package com.euq.service.Impl;

import com.euq.entity.Role;
import com.euq.mapper.RoleMapper;
import com.euq.mapper.UserMapper;
import com.euq.node.ZTreeNode;
import com.euq.service.RoleService;
import com.euq.utils.EuqException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.euq.enums.RoleID.ADMIN;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserMapper userMapper;
    @Override
    public PageInfo<Role> listAll(int page, int size) {
        PageHelper.startPage(page, size);
        List<Role> roles = roleMapper.listAll();
        return new PageInfo<>(roles);
    }

    @Override
    @CacheEvict(value = "roleCache", allEntries = true)
    public void delete(Long id) {
        if (id==0){
            throw new EuqException("9999","参数不能为空");
        }
        Role role=roleMapper.findById(id);
        if (role==null){
            throw new EuqException("9999","输入ID错误");
        }
        if (userMapper.findByRoleId(String.valueOf(id))!=null){
            throw new EuqException("9999","不能删除有用户使用的角色");
        }
        if(id<2){
            throw new EuqException("9999","不能删除初始角色");
        }
        if(id.equals(ADMIN.getValue())){
            throw new EuqException("9999","不能删除超级管理员");
        }
        roleMapper.delete(id);
    }

    @Override
    @Cacheable(value="roleCache",key = "T(String).format('%d,%d,%s,%s',#page,#size,#name,#tips)")
    public PageInfo<Role> selectRoles(int page, int size, String name, String tips) {
        PageHelper.startPage(page, size);
        List<Role> roles =roleMapper.selectRoles(name,tips);
        return new PageInfo<>(roles);
    }

    @Override
    @CacheEvict(value = "roleCache", allEntries = true)
    public void save(String name, String tips, Long deptId, Long pid, int num) {
        Role role=roleMapper.check(name,tips,deptId);
        if(role==null){
            roleMapper.insert(name,tips,deptId,pid,num);
        }else {
            roleMapper.update(name,tips,deptId,pid,num, role.getId());
        }
    }

    @Override
    public List<ZTreeNode> getRoleTreeNodes() {
        List<Role> roles = roleMapper.listAll();
        List<ZTreeNode> nodeList = new ArrayList<>();
        for (Role role : roles) {
            ZTreeNode node = new ZTreeNode();
            node.setId(role.getId());
            node.setpId(role.getPid());
            node.setName(role.getName());
            node.setOpen(true);
            node.setChecked(false);
            nodeList.add(node);
        }
        nodeList.add(ZTreeNode.createParent());
        return nodeList;
    }
}
